package cc.sunni.admin.service.impl;

import cc.sunni.admin.mapper.CategoryDao;
import cc.sunni.admin.service.CategoryService;
import cc.sunni.common.Constant;
import cc.sunni.common.exception.RRException;
import cc.sunni.common.utils.RedisOperator;
import cc.sunni.common.utils.ResultEnum;
import cc.sunni.pojo.Category;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category> implements CategoryService {
    @Autowired
    private RedisOperator redis;

    @Transactional
    @Override
    public void createCategory(Category category) {
        // 分类不会很多，所以id不需要自增，这个表的数据也不会多到几万甚至分表，数据都会集中在一起
        int result = baseMapper.insert(category);
        if (result != 1) {
            throw new RRException(ResultEnum.SYSTEM_OPERATION_ERROR);
        }
        // 直接使用redis删除缓存即可，用户端在查询的时候会直接查库，再把最新的数据放入到缓存中
        redis.del(Constant.REDIS_ALL_CATEGORY);
    }

    @Transactional
    @Override
    public void modifyCategory(Category category) {
        int result = baseMapper.updateById(category);
        if (result != 1) {
            throw new RRException(ResultEnum.SYSTEM_OPERATION_ERROR);
        }
        // 直接使用redis删除缓存即可，用户端在查询的时候会直接查库，再把最新的数据放入到缓存中
        redis.del(Constant.REDIS_ALL_CATEGORY);
    }

    @Override
    public boolean queryCatIsExist(String catName, String oldCatName) {
        List<Category> catList = baseMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getName, catName)
                .ne(StrUtil.isNotBlank(oldCatName), Category::getName, oldCatName));
        boolean isExist = false;
        if (CollectionUtil.isNotEmpty(catList)) {
            isExist = true;
        }
        return isExist;
    }

    @Override
    public List<Category> queryCategoryList() {
        return list();
    }
}